package com.token.iot.bratterycharging.gateway.business;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.outstanding.framework.base.mq.MQProducer;
import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.TransactionContext;
import com.outstanding.framework.log.LoggerFactory;
import com.token.iot.bratterycharging.gateway.AbstractOper;

import com.token.iot.bratterycharging.gateway.IDGeneration;
import com.token.iot.bratterycharging.gateway.IMEI;
import com.token.iot.bratterycharging.gateway.OperExchanger;
import com.token.iot.bratterycharging.gateway.api.Constant;
import com.token.iot.bratterycharging.gateway.api.LocalFee;
import com.token.iot.bratterycharging.gateway.utils.ByteUtil;

import io.netty.channel.ChannelHandlerContext;

/**
 * 刷卡状态响应
 * 
 * @author chenzhixuan
 *
 */
@Component("COIOper")
public class COIOper extends AbstractOper {
	@Autowired
	private MQProducer mQProducer;

	private static Logger loger = LoggerFactory.getLogger(DCEOper.class);

	@Override
	public int onCall(byte[] b, ChannelHandlerContext ctx) throws PendingException {
		String val = new String(b);
		// loger.info(" the COI response =" + val);
		String imei = IMEI.getIMEI(ctx);
		String sessionid = IDGeneration.getSessionID(b);
		String left = val.substring(14);
		String[] params = left.split("#/#");
		// 代表了扣款成功
		if (params[5].equals("1")) {
			LocalFee lf = new LocalFee();
			lf.setFeeType(11);
			lf.setCard(params[0]);
			lf.setTime(new Date());
			try {
				int amount = Integer.parseInt(params[1]);
				lf.setAmount(amount);
				int balance = Integer.parseInt(params[2]);
				lf.setBalance(balance);
			} catch (Exception e) {
				loger.error(e);
			}
			Gson gs = new Gson();
			String str = gs.toJson(lf);
			mQProducer.sendMessageByQueue(Constant.MESSAGEHEAD+Constant.QueueOfflinePayed, str);

		}

		int lastPost = val.lastIndexOf("#/#");
		String no = val.substring(lastPost + 3);
		HashMap<String, String> map = new HashMap();
		map.put("NO", no);
		TransactionContext.putData(Constant.PARAMS, map);
		TransactionContext.putData(Constant.SENDER, "DLB");
		return 1;
	}

}
